package server.socket.db;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.socket.bean.Message;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;

import java.util.List;

public class ChatModel {
    //登录后获取未读的消息
    public static List<Message> getMessage(int userId) {
        String sql = "select message as json from chat where user_id = ?";
        List<Message> messages = DBFactory.getDBDriver().query(sql, new BeanListHandler<>(Message.class, DBDriver.getProcess()), userId);
        deleteMessage(userId);
        return messages;
    }

    //向数据库中添加消息
    public static Info addMessage2DB(int userId, String message) {
        String sql = "insert into chat values(?,?)";
        int line = DBFactory.getDBDriver().update(sql, userId, message);
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }

    //删除数据库中的未读消息
    public static Info deleteMessage(int userId) {
        String sql = "delete from chat where user_id = ?";
        int line = DBFactory.getDBDriver().update(sql, userId);
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }
}
